package controllers

import (
	//"bufio"
	"fmt"
	//"io"
	//"io/ioutil"
	"log"
	//"net/http"
	//"regexp"
	"strings"
	m "xwaf_admin/models"

	//"unicode/utf8"
	//"time"
	//"github.com/astaxie/beego"
	//admlib "xwaf_admin/xadmin/src/lib"
	"github.com/tidwall/gjson"
	//"golang.org/x/text/encoding/simplifiedchinese"
)

type WafBlackIpController struct {
	CommonController
}

//列表/xwaf/blackip/v1/List
func (this *WafBlackIpController) List() {
	appname := this.GetString("appname")
	ip := this.GetString("ip")
	id, _ := this.GetInt64("id")
	page, _ := this.GetInt64("page")
	page_size, _ := this.GetInt64("limit")
	if this.Ctx.Request.Method == "POST" {
		gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
		appname = gp.Get("appname").String()
		ip = gp.Get("ip").String()
	}
	datas, count := m.GetXf_waf_blackipList(appname, ip, id, page, page_size)
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
	this.ServeJSON()
}

func (this *WafBlackIpController) Iplist() {
	appname := this.GetString("appname")
	//用于判断是第一次加载，后续获取变动的IP列表。
	cfgv := this.GetString("cfgv")

	AuthToken := this.Ctx.Request.Header.Get("Auth-Token")
	if AuthToken != ApiToken {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "ApiTokenFail", "count": 0}
		this.ServeJSON()
		return
	}

	datas, count := m.GetBlackIp(appname, cfgv)
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
	this.ServeJSON()
}

//添加
func (this *WafBlackIpController) Add() {
	u := m.Xf_waf_blackip{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("appname").Exists() {
		u.Appname = gp.Get("appname").String()
		u.Ip = gp.Get("ip").String()
		u.Expiretime = gp.Get("expiretime").String()
		u.Remarks = gp.Get("remarks").String()
		id, err := m.AddXf_waf_blackip(&u)
		if err == nil && id > 0 {
			log.Printf("[INFO] Add success")
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] Add Fail:%s", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
		}
	} else {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "bodyParseFail"}
		this.ServeJSON()
	}
}

func (this *WafBlackIpController) Update() {
	u := m.Xf_waf_blackip{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("appname").Exists() {
		u.Appname = gp.Get("appname").String()
		u.Ip = gp.Get("ip").String()
		u.Remarks = gp.Get("remarks").String()
		id, err := m.UpdateXf_waf_blackip(&u)
		if err == nil && id > 0 {
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] update blackip Fail:%s\n", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
		}
	} else {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "bodyParseFail"}
		this.ServeJSON()
	}
}

// //删除
func (this *WafBlackIpController) Del() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	Id, _ := this.GetInt64("id")
	appname := this.GetString("appname")
	respid, err := m.DelIpById(Id, appname)
	if err == nil && respid > 0 {
		log.Printf("[INFO] Delsuccess")
		this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
	} else {
		log.Printf("[ERROR] Del Error:%s\n", err.Error())
		this.Ctx.WriteString(`{"code":-1,"msg":"Error"}`)
	}
}

func (this *WafBlackIpController) Edit() {
	id := this.GetString("id")
	appname := this.GetString("appname")
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("name").Exists() {
		name := gp.Get("name").String()
		value := gp.Get("value").String()
		if appname == "" {
			appname = gp.Get("appname").String()
		}
		_, err := m.EditBlackIp(id, appname, name, value)
		if err == nil {
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] update blackip Fail:%s\n", err)
			this.Ctx.WriteString(fmt.Sprintf(`{"code":-1,"msg":"%s"}`, err.Error()))
		}
	} else {
		this.Ctx.WriteString(`{"code":-1,"msg":"bodyParseFail"}`)
	}
}

//将所有黑名单禁用时长过期的IP设置为禁用
func (this *WafBlackIpController) DisableExpireIp() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	num, err := m.DisableExpireTimeIp()
	if err != nil {
		log.Printf("[ERROR] DisableExpireIp Fail:%s\n", err)
		this.Ctx.WriteString(`{"code":1,"msg":"fail"}`)
		return
	}
	//delip
	_, _ = m.DelIpByStatusIsDelete()

	log.Printf("[INFO] DisableExpireIp success result:%d\n", num)
	this.Ctx.WriteString(fmt.Sprintf(`{"code":0,"msg":"%d"}`, num))
}

func (this *WafBlackIpController) JudgeWhiteListIp() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	var respmsg string
	ipstr := this.GetString("ip")
	var isExist = false
	for _, ip := range strings.Split(ipstr, ",") {
		iswhite, msg := m.JudgeWhiteIp(ip)
		if iswhite {
			respmsg += msg + ","
			isExist = true
		}
	}
	if isExist {
		this.Ctx.WriteString(fmt.Sprintf(`{"code":0,"msg":"%s"}`, strings.TrimRight(respmsg, ",")))
		return
	}
	this.Ctx.WriteString(`{"code":-1,"msg":"noWhiteListip"}`)
}
